/******************************************************************************
 * Copyright (C) 2012 ShenZhen ComTop Information Technology Co.,Ltd
 * All Rights Reserved.
 * 本软件为深圳康拓普开发研制�?未经本公司正式书面同意，其他任何个人、团体不得使用�?
 * 复制、修改或发布本软�?
 *****************************************************************************/

package com.code.common.nio;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.zip.GZIPInputStream;

import org.apache.log4j.Logger;


/**
 * 解析Socket对象
 *
 * @author 陈大�?
 * @since 1.0
 * @version 2012-11-29 陈大�?
 */
public class FileReceivingTask implements Runnable {

    /** Log的对�?*/
    private final static Logger LOG = Logger.getLogger(FileReceivingTask.class);

    /** 用于解压Socket的压缩流 */
    private GZIPInputStream objGZIPInputStream = null;

    /** 用于返回Socket的压缩流对象 */
    private ObjectInputStream objObjectInputStream = null;

    private BlockingQueue<Map<String, List<Map<String, Object>>>> objBlockQueue = null;

    public FileReceivingTask(Socket socket, BlockingQueue<Map<String, List<Map<String, Object>>>> objBlockQueue) {
        this.objBlockQueue = objBlockQueue;
        try {
            objGZIPInputStream = new GZIPInputStream(socket.getInputStream());
            objObjectInputStream = new ObjectInputStream(objGZIPInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        getObjectInputStream();
    }

    /**
     * 从Socket中解析对�?
     *
     * @return objMonitorInfo
     */
    @SuppressWarnings("unchecked")
    private Object getObjectInputStream() {
        Object objMonitorInfo = null;
        try {

            synchronized (objBlockQueue) {
                while (objObjectInputStream.read() < objObjectInputStream.available())
                    objBlockQueue.offer((Map<String, List<Map<String, Object>>>) objObjectInputStream.readObject());
            }

        } catch (IOException e) {
            LOG.error("解压Socket异常", e);
        } catch (ClassNotFoundException e) {
            LOG.error("从Socket流中解析对象异常", e);
        } finally {
            if (objObjectInputStream != null) {
                try {
                    objObjectInputStream.close();
                } catch (IOException e) {
                }
            }
            if (objGZIPInputStream != null) {
                try {
                    objGZIPInputStream.close();
                } catch (IOException e) {
                }
            }
        }
        return objMonitorInfo;
    }
}